<template>
  <div>
    
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框 -->

      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            class="input-with-select"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            v-model.trim="queryInfo.query"
            @change="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="usersList" style="width: 100%" border stripe>
        <!-- prop表示渲染数据源的某个属性 ,label表示该列的名称-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>

        <el-table-column prop="mg_state" label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409eff"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <div>
              <!-- 修改按鈕-->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEdit(scope.row.id)"
              ></el-button>
              <!-- 刪除按鈕 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUser(scope.row.id)"
              ></el-button>
              <!-- 分配角色按鈕 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="分配按钮"
                placement="top-start"
              >
                <el-button
                  type="info"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setrole(scope.row)"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addCloseDialog"
    >
      <!-- 内容区 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="90px"
        status-icon
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model.trim="addForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model.trim="addForm.password"
            clearable
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="addForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model.trim="addForm.mobile" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="60%"
    @close="editCloseDialog">
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
      <!-- 分配按钮对话框 -->
      <el-dialog
  title="分配角色"
  :visible.sync="allotDialogVisible"
  width="60%"
>
  <div>
    <p>当前的用户{{allotRole.username}}</p>
    <p class="allot_role">当前的角色{{allotRole.role_name}}</p>
    <p>分配新角色：
  <el-select v-model="roleValue" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="allotDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotUsersInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  name: "users",
  data() {
    // 验证邮箱规则
    let checkEmail = (rule, value, cb) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      // 返回为TRUE代表合法
      if (reg.test(value)) {
        console.log(rule);
        return cb();
      }
      cb(new Error("请输入合法邮箱"));
    };

    // 验证手机号规则
    let checkMobile = (rule, value, cb) => {
      const reg = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
      // 返回为TRUE代表合法
      if (reg.test(value)) {
        return cb();
      }
      cb(new Error("请输入正确手机号"));
    };
    return {
      queryInfo: { query: "", pagenum: 1, pagesize: 2 }, //pagesize代表当前页有几条数据，pagenum表示第几页
      usersList: [],
      total: 0,
      dialogVisible: false, //添加用户弹出框显示
      editDialogVisible: false, //修改用户对话框显示与隐藏
      addForm: {
        //添加用户表单数据
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {}, //查询到的用户信息
      addRules: {
        //表单验证规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名请在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码请在6 到 15 个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      allotDialogVisible:false,//分配按钮对话框显示与隐藏
      allotRole:{},//分配角色的用户信息
      rolesList:[],//角色列表信息
      roleValue:'',//用户选中的角色
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data } = await this.$http("users", { params: this.queryInfo });
      if (data.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.usersList = data.data.users;
      this.total = data.data.total;
      console.log(data);
    },
    // 监听pagesize改变的事件
    handleSizeChange(size) {
      // console.log(size);
      this.queryInfo.pagesize = size;
      this.getUserList();
    },
    // 监听页码值改变的事件
    handleCurrentChange(page) {
      console.log(page);
      this.queryInfo.pagenum = page;
      this.getUserList();
    },
    // 用户状态变化事件
    async userStateChange(userinfo) {
      console.log(userinfo);
      const { data } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (data.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 监听添加用户对话框的关闭
    addCloseDialog() {
      this.$refs.addFormRef.resetFields();
    },
    //监听修改用户对话框的关闭
    editCloseDialog(){
      this.$refs.editFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          this.dialogVisible = false;
          return this.$message.error("信息错误");
        }
        const { data } = await this.$http.post("users", this.addForm);
        console.log(data);
        if (data.meta.status !== 201) {
          this.$message.error(data.meta.msg);
        } else {
          this.$message.success("添加用户成功");
        }
        //隐藏用户对话框
        this.dialogVisible = false;
        // 重新获取用户列表
        this.getUserList();
      });
    },
    //修改用户前获取用户信息
    async showEdit(id) {
      const { data } = await this.$http.get(`users/${id}`);
      if (data.meta.status !== 200) {
        return this.$message.error("获取用户信息失败");
      }
      this.editForm = data.data;
      this.editDialogVisible = true;
    },
    // 修改用户信息
    editFormInfo(){
     this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          this.editCloseDialog = false;
          return this.$message.error("信息错误");
        }
        const { data } = await this.$http.put(`users/${this.editForm.id}`, {
          email:this.editForm.email,mobile:this.editForm.mobile
        });
        console.log(data);
        if (data.meta.status !== 200) {
          this.$message.error(data.meta.msg);
        } else {
          this.$message.success("修改用户成功");
        }
        //隐藏用户对话框
        this.editDialogVisible = false;
        // 重新获取用户列表
        this.getUserList();
        
      }
     )
    },
    //根据ID删除用户
    async removeUser(id){
    // 弹框确认用户是否删除
     const confirmResult=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        ;
        // 用户确认删除
        // 用户确认删除，返回值是confirm
        // 取消返回值是cancel
        if(confirmResult!=='confirm'){
          return this.$message.info('已取消删除')
        }
        // 用户确认删除，发送请求删除该数据
        const {data}=await this.$http.delete(`users/${id}`)
        console.log(data);
        if(data.meta.status!==200) return this.$message.error(data.meta.msg)
         this.$message.success('删除成功')
         this.getUserList()
    },
    // 分配角色对话框显示
   async setrole(role){
        this.allotRole=role;
       const {data,}=await this.$http.get('roles');
       if(data.meta.status!==200){
         return this.$message.error('请求信息失败')
       }
       this.rolesList=data.data;
       console.log(this.rolesList);
     this.allotDialogVisible=true;
    },
    // 分配角色
    async allotUsersInfo(){
    if(!this.roleValue){
      this.$message.error('请选择一个角色');
    }
    let roleValueId=window.Number(this.allotRole.id);
   const {data,}=await this.$http.put(`users/${roleValueId}/role`,{
    rid:this.roleValue
   });
   console.log(data);
   if(data.meta.status!==200){
         return this.$message.error('请求信息失败')
       }
       this.$message.success('更改角色成功');
       this.getUserList();
       this.allotDialogVisible=false;
     }
},}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.allot_role{
  margin: 15px  auto;
}
</style>